import numpy as np

# 读取数据
try:
    r = np.genfromtxt('LearningData2.csv', delimiter=',', skip_header=1, dtype=str)
except:
    r = np.genfromtxt('Works/第4章朴素贝叶斯法/LearningData2.csv', delimiter=',', skip_header=1, dtype=str)

# 定义先验概率和条件概率的字典
prior = {}
conditional = {}
counts_y = {}  # 用于存储每个类别的数量

# 计算先验概率并存储到prior字典,counts_y存储每个类别的数量
labels, counts = np.unique(r[:, -1], return_counts=True)
total = len(r)
for label, count in zip(labels, counts):
    prior[label] = count / total
    counts_y[label] = count

# 计算条件概率并存储到conditional字典
for i in range(1,5): # 遍历每个特征列
    combos, counts = np.unique(r[:,[i,-1]],axis=0,return_counts=True)
    total = len(r)
    for combo,count in zip(combos,counts):
        conditional[tuple(combo)] = count / counts_y[combo[1]]

# 输入X的值
print('请输入Outlook:')
X1 = str(input())
print('请输入Temperature:')
X2 = str(input())
print('请输入Humidity:')
X3 = str(input())
print('请输入Wind:')
X4 = str(input())

# 计算后验概率
probability = {}
for label in labels:
    probability[label] = prior[label] * conditional.get((X1,label),0) * conditional.get((X2,label),0) * conditional.get((X3,label),0) * conditional.get((X4,label),0)

# 输出结果
print("由朴素贝叶斯法得出PlayTennis=", max(probability, key=probability.get))